package com.lu.servlet;

import com.lu.dao.impl.NewsDaoImpl;
import com.lu.entity.News;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Random;

public class AddNewsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        resp.setContentType("text/html");
        PrintWriter out = resp.getWriter();

        int ntid = 0;
        String ntitle = null;
        String nauthor = null;
        String nsummary = null;
        String ncontent = null;
        String npicPath = null;
        News news = null;
        boolean isMultipart = ServletFileUpload.isMultipartContent(req);
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            try {
                // 通过请求对象 request 转成一个元素集合 来获取数据
                List<FileItem> items = upload.parseRequest(req);

                String uploadFilePath = req.getSession().getServletContext().getRealPath("upload/");
                Random random = new Random(System.currentTimeMillis());

                for (FileItem item : items) {
                    if (item.isFormField()) { // 普通元素 k-v name-value
                        if (item.getFieldName().equals("ntid")) {
                            ntid = Integer.parseInt(item.getString("utf-8"));
                        } else if (item.getFieldName().equals("ntitle")) {
                            ntitle = item.getString("utf-8");
                        } else if (item.getFieldName().equals("nauthor")) {
                            nauthor = item.getString("utf-8");
                        } else if (item.getFieldName().equals("nsummary")) {
                            nsummary = item.getString("utf-8");
                        } else if (item.getFieldName().equals("ncontent")) {
                            ncontent = item.getString("utf-8");
                        }
                    } else { // 文件元素 指定上传的目录
                        String fileName = item.getName(); // 获取客户端的文件名称
                        // 不为空 不为0长度
                        if (fileName != null && fileName.length() != 0) {
                            // 产生随机的新文件名称 保留原有的 .文件后缀
                            String saveName = "" + System.currentTimeMillis() + random.nextInt(10000) + fileName.substring(fileName.lastIndexOf("."));
                            File saveFile = new File(uploadFilePath, saveName); // 生成上传的文件
                            try {
                                item.write(saveFile); // 完成上传
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                            npicPath = "upload/" + saveName; // 这是一个相对路径 保存到数据库中 图片路径
                        }
                    }
                }
            } catch (FileUploadException e) {
                throw new RuntimeException(e);
            }
            news = new News(ntid, ntitle, nauthor, npicPath, ncontent, nsummary);
        } else {
            ntid = Integer.parseInt(req.getParameter("ntid"));
            ntitle = req.getParameter("ntitle");
            nauthor = req.getParameter("nauthor");
            nsummary = req.getParameter("nsummary");
            ncontent = req.getParameter("ncontent");
            news = new News(ntid, ntitle, nauthor, ncontent, nsummary);
        }


        // 不能使用请求对象 request 直接获取表单数据
//    int ntid = Integer.parseInt(request.getParameter("ntid"));
//    String ntitle = request.getParameter("ntitle");
//    String nauthor = request.getParameter("nauthor");
//    String nsummary = request.getParameter("nsummary");
//    String ncontent = request.getParameter("ncontent");


        int result = new NewsDaoImpl().insertOneNews(news);
        if (result > 0) {
            out.print("<script>alert('添加成功!')</script>");
            out.print("<script>location.href='GetSomeNewsByPageServlet';</script>");
        } else {
            out.print("<script>alert('添加失败!')</script>");
            out.print("<script>history.back();</script>");
        }


        out.flush();
        out.close();
    }
}
